﻿using Masuit.Tools.Strings;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace CoreManager.Common
{
    public  class CaptchaGenerator
    {
        private static readonly Random _random = new Random();
        /// <summary>
        /// 生成随机验证码
        /// </summary>
        /// <param name="length">长度</param>
        /// <returns>随机字符串</returns>
        public static string GenerateRandomCode(int length)
        {
            const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 排除容易混淆的字符
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[_random.Next(s.Length)]).ToArray());
        }

        public static string GenerateCaptcha(int length)
        {
            return ValidateCode.CreateValidateCode(length);
        }


        /// <summary>
        /// 生成唯一请求ID
        /// </summary>
        /// <returns>请求ID</returns>
        public  static string GenerateRequestId()
        {
            return Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// 生成验证码图片
        /// </summary>
        /// <param name="captchaCode">验证码文本</param>
        /// <returns>图片字节数组</returns>
        public static byte[] GenerateCaptchaImage(string captchaCode)
        {
            int width = 120;
            int height = 40;

            using var image = new Image<Rgba32>(width, height);

            // 填充背景色
            image.Mutate(ctx => ctx.Fill(SixLabors.ImageSharp.Color.White));

            // 添加干扰线
            for (int i = 0; i < 5; i++)
            {
                var color = GetRandomColor();
                var p1 = new PointF(_random.Next(0, width), _random.Next(0, height));
                var p2 = new PointF(_random.Next(0, width), _random.Next(0, height));
                image.Mutate(ctx => ctx.DrawLine(color, 1, p1, p2));
            }

            // 添加干扰点
            for (int i = 0; i < 80; i++)
            {
                var point = new PointF(_random.Next(0, width), _random.Next(0, height));
                image.Mutate(ctx => ctx.Fill(GetRandomColor(), new RectangleF(point.X, point.Y, 2, 2)));
            }

            try
            {
                // 尝试加载字体
                var fontCollection = new FontCollection();
                var fontFamily = fontCollection.Add("Arial");
                var font = fontFamily.CreateFont(24, FontStyle.Bold);

                // 绘制验证码文本
                for (int i = 0; i < captchaCode.Length; i++)
                {
                    var textOptions = new TextOptions(font)
                    {
                        Origin = new PointF(8 + i * 20, 8 + _random.Next(-5, 5)),
                        HorizontalAlignment = HorizontalAlignment.Left,
                        VerticalAlignment = VerticalAlignment.Top
                    };

                    // 随机旋转角度
                    float angle = _random.Next(-15, 15);
                    image.Mutate(ctx => ctx
                        .Rotate(angle)
                        .DrawText(captchaCode[i].ToString(), font, GetRandomDarkColor(), new PointF(8 + i * 20, 8 + _random.Next(-5, 5)))
                        .Rotate(-angle));
                }
            }
            catch
            {
                // 如果字体加载失败，使用简单方式绘制文本
                image.Mutate(ctx => ctx.DrawText(captchaCode, SystemFonts.CreateFont("Arial", 24), Color.Black, new PointF(10, 10)));
            }

            // 输出为PNG格式
            using var memoryStream = new MemoryStream();
            image.Save(memoryStream, new PngEncoder());
            return memoryStream.ToArray();
        }

        /// <summary>
        /// 获取随机颜色
        /// </summary>
        /// <returns>随机颜色</returns>
        private static SixLabors.ImageSharp.Color GetRandomColor()
        {
            return SixLabors.ImageSharp.Color.FromRgb(
                (byte)_random.Next(0, 256),
                (byte)_random.Next(0, 256),
                (byte)_random.Next(0, 256));
        }

        /// <summary>
        /// 获取随机深色
        /// </summary>
        /// <returns>随机深色</returns>
        private static SixLabors.ImageSharp.Color GetRandomDarkColor()
        {
            return SixLabors.ImageSharp.Color.FromRgb(
                (byte)_random.Next(0, 128),
                (byte)_random.Next(0, 128),
                (byte)_random.Next(0, 128));
        }
    }
}
